package com.kx.game.center.async;

import com.alibaba.fastjson.JSONObject;
import com.genchance.core.dawn.util.TimeUtils;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.common.ServerEnum;
import com.kx.game.center.manager.AsyncTaskManager;
import com.kx.game.center.redis.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ListenerServer {

    private static Logger logger = LoggerFactory.getLogger(ListenerServer.class);

    public ListenerServer() {
        //每11分钟执行一次的timer
        AsyncTaskManager.getInstance().addTimerTaskWithFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, TimeUtils.MINUTE * 10, TimeUtils.MINUTE * 11);
    }

    public void execute() throws Exception {
        if (!GSServices.loadManager.getRedisState()) {
            logger.info(" ========================= redis数据未初始化完成");
            return;
        }
        logger.info(" ========================= 服务器状态监测开始");
        List<JSONObject> jsonObjects = GSServices.redisManager.hashValues(RedisConstant.GAME_SERVER_LIST, JSONObject.class);
        for (JSONObject jsonObject : jsonObjects) {
            long time = Long.valueOf(jsonObject.getString("time"));
            if (jsonObject.getString("state").equals(ServerEnum.START.getIndex() + "") && System.currentTimeMillis() - time > TimeUtils.MINUTE * 10) {
                jsonObject.put("state", ServerEnum.STOPERROR.getIndex() + "");
                String serverId = jsonObject.getString("serverId");
                boolean insert = GSServices.redisManager.hashSetNX(RedisConstant.GAME_SERVER_LIST, serverId, jsonObject);
                if (!insert)
                    GSServices.redisManager.hashSet(RedisConstant.GAME_SERVER_LIST, serverId, jsonObject);
                GSServices.localManager.deleteGameServerLoginCount(serverId);
                logger.info(" ========================= 服务器长时间未响应 {}" + jsonObject);
            }
        }
        logger.info(" ========================= 服务器状态监测结束");
    }
}
